/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Models.Validators;

import com.dpy.appmvdpy.Facades.ClientesFacade;
import com.dpy.appmvdpy.Facades.UsersFacade;
import com.dpy.appmvdpy.Models.AlteraSenha;
import com.dpy.appmvdpy.Models.Clientes;
import com.dpy.appmvdpy.Models.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

/**
 *
 * @author ac_psoares
 */
@Component
@Scope(value="request")
public class AlteraSenhaValidator extends DefaultValidator<AlteraSenha> {

    @Autowired
    public UsersFacade facade;

    @Override
    public boolean supports(Class<?> type) {
        return AlteraSenha.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "senhaAtual","required.senhaAtual", "Senha Atual não informada!");
        
       
        AlteraSenha senha = (AlteraSenha)o;
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Users users = facade.getByUsername(user.getUsername());
        System.out.println(senha.getSenhaAtual());
        System.out.println(senha.getNovaSenha());
        System.out.println(senha.getConfirmaNovaSenha());
        if(user.getPassword() == null ? senha.getSenhaAtual() != null : !user.getPassword().equals(senha.getSenhaAtual()))
            errors.rejectValue("senhaAtual", "match.senhaAtual", "Senha atual não confere!");        
        
        if(senha.getNovaSenha() == null ? senha.getConfirmaNovaSenha() != null : !senha.getNovaSenha().equals(senha.getConfirmaNovaSenha()))
            errors.rejectValue("novaSenha", "match.novaSenha", "Senhas não conferem!");       
       
        
    }
    
}
